//
//  CurrentEventSearchController.m
//  Runone
//
//  Created by ekkaLyn on 2017/3/18.
//  Copyright © 2017年 runone. All rights reserved.
//

#import "CurrentEventSearchController.h"
#import "CJCalendarViewController.h"
#import "EventBaseCell.h"
#import "MJRefresh.h"
#import "RequestHelper.h"
#import "MJExtension.h"
#import "AppConstants.h"
#import "TollEvent.h"

#import "CurrentContructDetailViewController.h"
#import "CurrentIncidentDetailViewController.h"
#import "AppLocalManager.h"
#import "UnStartEventController.h"
#import "InprogressController.h"
#import "SVProgressHUD.h"

@interface CurrentEventSearchController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource,CalendarViewControllerDelegate, UIPopoverPresentationControllerDelegate>
@property (strong, nonatomic) UISearchBar *searchBar;
@property (nonatomic,strong)UIView *meesageV;
@property (nonatomic, strong)UIButton *calendarBtn;
@property (strong, nonatomic) UITableView *tableView;

@property (assign, nonatomic) NSInteger currentPageIndex;
@property (assign, nonatomic) NSInteger currentSearchWay;
@property (copy  , nonatomic) NSString *searchContentStr;
@property (nonatomic, strong) NSString *EventType;

@property (strong, nonatomic) NSMutableArray *searchDataArray;
//@property (strong, nonatomic) NSString *textString;

@end

static NSString *cellID = @"searchCell";
@implementation CurrentEventSearchController

#pragma    ------施工事件搜索功能



- (void)viewDidLoad {
    [super viewDidLoad];
    //self.view.backgroundColor = [UIColor yellowColor];
    [self configDefault];
    [self configNavitationBar];
    [self configTableView];
    [self configCalendarBtn];
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    
    //self.tableView.backgroundColor = [UIColor blueColor];
}

- (void) configDefault {
//    self.automaticallyAdjustsScrollViewInsets = NO;
    NSInteger inter = _titleType;
    NSInteger eIn    = inter + 1;
    _EventType       = [NSString stringWithFormat:@"%ld", (long)eIn];
    self.searchDataArray = [[NSMutableArray alloc] init];
   self.view.backgroundColor = [UIColor colorWithRed:226.0 / 255 green:230.0 / 255 blue:240.0 / 255 alpha:1];
}

- (void)configNavitationBar {
    _searchBar = [[UISearchBar alloc] init];
    _searchBar.placeholder = @"请输入搜索的关键字";
    self.navigationItem.titleView = _searchBar;
    _searchBar.delegate = self;
    [_searchBar becomeFirstResponder];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"left_narrow"] style:UIBarButtonItemStylePlain target:self action:@selector(popBack)];
}

- (void) popBack {
 [self.navigationController popViewControllerAnimated:YES];
}

- (void)configCalendarBtn {
    _calendarBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _calendarBtn.backgroundColor    = [UIColor lightGrayColor];
    [_calendarBtn setBackgroundImage:[UIImage imageNamed:@"btn_calendar"] forState:UIControlStateNormal];
    _calendarBtn.frame              = CGRectMake(self.view.bounds.size.width / 2 - 30, 118, 60, 60);
    _calendarBtn.layer.cornerRadius = 29;
    _calendarBtn.backgroundColor    = [UIColor whiteColor];
    _calendarBtn.clipsToBounds      = YES;
    [_calendarBtn addTarget:self action:@selector(calendarBtnClick)
           forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_calendarBtn];
}
- (void) calendarBtnClick {
    CJCalendarViewController *calendarController = [[CJCalendarViewController alloc] init];
    calendarController.view.frame = self.view.frame;
    calendarController.delegate   = self;
    [self presentViewController:calendarController animated:YES completion:nil];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self.searchBar resignFirstResponder];
    if([searchBar.text length] > 0) {  // 有输入
        [_searchBar resignFirstResponder];
        self.currentSearchWay = 1;
        NSString *contentStr  = searchBar.text;
        self.currentPageIndex = 1;
        self.searchContentStr = contentStr;
        [self searchDataFromServer:@"" pageIndex:1 pageSize:10 eventClass:_EventType searchWay:1 searchContentString:contentStr];
    }else { // 无输入
        return;
    }
}
#pragma mark - 日历控件的代理
-(void)CalendarViewController:(CJCalendarViewController *)controller didSelectActionYear:(NSString *)year month:(NSString *)month day:(NSString *)day{
    [_searchBar resignFirstResponder];
    self.currentSearchWay = 2;
    NSString *contentStr  = [NSString stringWithFormat:@"%@-%@-%@",year,month,day];
    self.currentPageIndex = 1;
    self.searchContentStr = contentStr;
    [self searchDataFromServer:@"" pageIndex:1 pageSize:10 eventClass:_EventType searchWay:2 searchContentString:contentStr];
}

- (void)configTableView {
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    [self.view addSubview:_tableView];
    _tableView.dataSource = self;
    _tableView.delegate   = self;
    _tableView.hidden     = YES;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self.tableView registerNib:[UINib nibWithNibName:@"EventBaseCell" bundle:nil] forCellReuseIdentifier:cellID];
    self.tableView.mj_footer.hidden = YES;
    self.tableView.mj_footer        = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(searchMoreData)];
   
}
#pragma mark - 请求
-(NSString *)DataValueStr:(NSString *)lastEventUID pageIndex:(NSString *)pageIndex pageSize:(NSString *)pageSize eventClass:(NSString *)eventClass searchWay:(NSString *)searchWay searchContent:(NSString *)searchContent {
    NSString *valueStr =[NSString stringWithFormat:@"[{\"Key\":\"LastEventUID\",\"Value\":\"%@\"},{\"Key\":\"PageIndex\",\"Value\":\"%@\"},{\"Key\":\"PageSize\",\"Value\":\"%@\"},{\"Key\":\"EventClass\",\"Value\":\"%@\"},{\"Key\":\"SearchWay\",\"Value\":\"%@\"},{\"Key\":\"SearchContent\",\"Value\":\"%@\"}]",lastEventUID,pageIndex,pageSize,eventClass,searchWay,searchContent];
    NSLog(@"%@",valueStr);
    return valueStr;
}
- (void)searchDataFromServer:(NSString *)lastUID  pageIndex:(NSInteger)pIndex pageSize:(NSInteger)pSize eventClass:(NSString *)eClass searchWay:(NSUInteger )sWay searchContentString:(NSString *) contetentStr{
    
    [_searchBar resignFirstResponder];
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *SearchEventModel=[[RequestGinsengModel alloc] init];
    SearchEventModel.URL         = GetEventDataURL;
    SearchEventModel.DataValue   = [self DataValueStr:lastUID pageIndex:[NSString stringWithFormat:@"%ld",(long)pIndex] pageSize:[NSString stringWithFormat:@"%ld",(long)pSize] eventClass:eClass searchWay:[NSString stringWithFormat:@"%ld",(unsigned long)sWay] searchContent:contetentStr];
    SearchEventModel.UpdatedTime = @"";
    SearchEventModel.SystemCode  = @"GuangleHighway";
    SearchEventModel.MethodName  = @"SearchEvent";
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
        if ([requestOutginseng.Code isEqualToString:@"001"]) {
            _searchDataArray = [CurrentEvent mj_objectArrayWithKeyValuesArray:requestOutginseng.DataValue];
            self.calendarBtn.hidden = YES;
            self.tableView.hidden   = NO;
            [self.tableView reloadData];
        }
        [self.tableView.mj_footer endRefreshing];
    };
    [requestHelper RequestGinsengModel:SearchEventModel andPushController:self];
}

- (void) searchMoreData {
   
    self.currentPageIndex += 1;
    CurrentEvent *model = [self.searchDataArray lastObject];
    
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *SearchEventModel=[[RequestGinsengModel alloc] init];
    SearchEventModel.URL         = GetEventDataURL;
    SearchEventModel.DataValue   = [self DataValueStr:model.IncidentUID pageIndex:[NSString stringWithFormat:@"%ld",(long)self.currentPageIndex] pageSize:@"10" eventClass:self.EventType searchWay:[NSString stringWithFormat:@"%ld",(unsigned long)self.currentSearchWay] searchContent:self.searchContentStr];
    SearchEventModel.UpdatedTime = @"";
    SearchEventModel.SystemCode  = @"GuangleHighway";
    SearchEventModel.MethodName  = @"SearchEvent";
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
        if ([requestOutginseng.Code isEqualToString:@"001"]) {
            NSArray *array = [TollEvent mj_objectArrayWithKeyValuesArray:requestOutginseng.DataValue];
            [self.searchDataArray addObjectsFromArray:array];
            self.calendarBtn.hidden = YES;
            [self.tableView reloadData];
        }else {
            self.currentPageIndex -= 1;
        }

        [self.tableView.mj_footer endRefreshing];
    };
    [requestHelper RequestGinsengModel:SearchEventModel andPushController:self];
}

- (void) confirmSearch {
    if (self.searchBar.text.length >1) {
        self.searchContentStr = self.searchBar.text;
        self.currentSearchWay = 1;
        self.currentPageIndex = 1;
        [self searchDataFromServer:@"" pageIndex:1 pageSize:10 eventClass:_EventType searchWay:1 searchContentString:self.searchBar.text];
    }
}

#pragma mark - tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.searchDataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EventBaseCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (_titleType == 0 || _titleType== 1 || _titleType == 3){ // 当前事件 历史事件 施工事件
        
        cell.backgroundColor = kViewBackGroundColor;
        CurrentEvent *model = self.searchDataArray[indexPath.row];
        
        if (_titleType == 3){
            cell.markInt = EventListTitleTypeConstruct;
        }
        if (_titleType == 1) {
            cell.markInt = EventListTitleTypeHistory;
        }
        if (_titleType == 0) {
            cell.markInt = EventListTitleTypeCurrent;
        }
        cell.ceModel = model;
    }
    if (_titleType == 2) {  //收费事件
        TollEvent *model = self.searchDataArray[indexPath.row];
        cell.tollData = model;
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(_titleType == 0 || _titleType == 3) {
        CurrentEvent *model = [_searchDataArray objectAtIndex:indexPath.row];
        CGFloat cellH;
        CGFloat height;
        if ((model.DealDetail)) {
            NSString *tempStr = model.DealDetail;
            
            cellH = [self caculateCellHeight:tempStr];
            int colun = cellH / 16; // 校准
            if (colun == 1) {
                height = 110;
            }else {
                height = cellH + 16 + 44 + 5 + 20 + 8 + colun * 0.293;
            }
            
        }else {
            height = 110;
        }
        return height;
        
    }else if (_titleType == 1) {
        CurrentEvent *model = [_searchDataArray objectAtIndex:indexPath.row];
        CGFloat cellH;
        CGFloat height;
        if ((model.Content)) {
            NSString *tempStr = model.Content;
            
            cellH = [self caculateCellHeight:tempStr];
            int colun = cellH / 16; // 校准
            if (colun == 1) {
                height = 110;
            }else {
                height = cellH + 16 + 44 + 5 + 20 + 8 + colun * 0.293;
            }
            
        }else {
            height = 110;
        }
        return height;
        
    }
    else {
        return 110;
    }
}

#pragma mark - 计算cell的高度
- (CGFloat) caculateCellHeight:(NSString *)string  {
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:14]};
    CGSize maxSize   = CGSizeMake([UIScreen mainScreen].bounds.size.width - 68, MAXFLOAT);
    CGFloat dealHeight = [string boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:attributes context:nil].size.height;
    return dealHeight;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_titleType == 0) { //当前事件
        CurrentEvent *model = _searchDataArray[indexPath.row];
        if ([model.IncidentParentType integerValue] == 3) {  //施工事件
            CurrentContructDetailViewController *vc= [[CurrentContructDetailViewController alloc] init];
            vc.CEModel = model;
            [self.navigationController pushViewController:vc animated:YES];
        } else {  //事故事件
            CurrentIncidentDetailViewController *vc = [[CurrentIncidentDetailViewController alloc] init];
            vc.CEModel = model;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
    
    if (_titleType == 3) { //施工事件
        CurrentEvent *model = _searchDataArray[indexPath.row];
        NSString *str     = [[AppLocalManager sharedManager] getDataByKey:SYSUSERUID];
        if ([model.RecordUserUID isEqualToString:str]) {
            if (model.State == 1) { // 未开始
                UnStartEventController *vc = [[UnStartEventController alloc] init];
                vc.reportModel              = model;
                [self.navigationController pushViewController:vc animated:YES];
            }
            if (model.State == 2) { // 进行中
                InprogressController *vc = [[InprogressController alloc]init];
                vc.reportModel               = model;
                [self.navigationController pushViewController:vc animated:YES];
            }
        } else {
            [SVProgressHUD showSuccessWithStatus:@"不能编辑他人事件"];
            return;
        }
    }
}

@end
